package com.gitee.luosl.cola.stream;


import java.util.Collections;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.stream.Stream;

public abstract class AbstractStreamWrapper<T> implements StreamWrapper<T> {

    private final Stream<T> stream;

    public AbstractStreamWrapper(Stream<T> stream) {
        this.stream = stream;
    }

    @Override
    public Stream<T> getStream() {
        return stream;
    }

    protected <K, S extends AbstractStreamWrapper<T>> S distinctBy(Function<T, K> byExtractor, Function<Stream<T>, S> mapper){
        final Set<Optional<K>> distSet = Collections.newSetFromMap(new ConcurrentHashMap<>());
        return mapper.apply(getStream().filter(item -> distSet.add(Optional.ofNullable(byExtractor.apply(item)))));
    }

}
